const CACHE_NAME = "Detect-SW-APP";
const CHANNEL_NAME = "detect";

self.addEventListener("install", function(event) {
  self.skipWaiting();
  event.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) {
      return cache.add("./sw.jpg");
    })
  );
});

self.addEventListener("activate", event => {
  event.waitUntil(clients.claim());
});

self.addEventListener("fetch", function(event) {
  if (/\.jpg$/.test(event.request.url)) {
    event.respondWith(
      caches.match("./sw.jpg").then(function(response) {
        if (response) {
          return response;
        }

        return fetch(event.request);
      })
    );
  }
});

self.addEventListener("push", function(event) {
  console.log("push", event);

  if (!(self.Notification && self.Notification.permission === "granted")) {
    return;
  }

  if (event.data) {
    try {
      var data = event.data.json();

      self.registration.showNotification(data.title, {
        body: data.body,
        icon: data.icon,
        tag: data.title + data.body + data.icon,
        data: data.data,
        requireInteraction: !0
      });
    } catch (e) {}
  }
});

self.addEventListener("notificationclick", function(event) {
  console.log("notificationclick", event);
  event.notification.close();
  event.notification.data.nav &&
    self.clients.openWindow(event.notification.data.nav);
});

self.addEventListener("pushsubscriptionchange", e => {
  console.log("pushsubscriptionchange", e);
});

/**
 * {type: '', data: {}}
 */
self.addEventListener("message", e => {
  console.log("message", e);

  if (e.data.type == "channel") {
    e.ports[0].postMessage("我是来自 sw 的消息");
  }

  if (e.data.type == "broadcast") {
    self.bc.postMessage("我是来自 sw 的广播消息");
  }

  if (e.data.type == "clients-broadcast") {
    clients
      .matchAll({
        type: "window"
      })
      .then(windows => {
        for (const win of windows) {
          win.postMessage("我是来自 sw 的clients广播消息");
        }
      });
  }
});

if ("BroadcastChannel" in self) {
  self.bc = new BroadcastChannel(CHANNEL_NAME);
}

self.addEventListener("sync", e => {
  // console.log("sync", e);
  // e.waitUntil(Promise.all([setTimeout(() => {
  //   console.log('waiting')
  //   return Promise.resolve()
  // }, 5000)]));
  // 放到 e.waitUnitel 里 reject 好像不会删除 tag
  e.waitUntil(
    new Promise((res, rej) => {
      console.log("sync", e);
      console.log(new Date());
      return rej();
    })
  );
  // 不 resolve 会一真重试
  // e.waitUntil(() => fetch("http://kjflskdfj.com/"));
  // setTimeout(
  //   () =>
  //     self.registration.sync.getTags().then(tags => {
  //       console.log("未完成 Sync Tags", tags);
  //     }),
  //   0
  // );
});
